//在该文件中使用APP引用，必须使用getApp()函数
var common = require("./common");
var getAll = common.getAll;
var login = common.login;
var signup = common.signup;
var dealWithUserInfo = common.dealWithUserInfo;


const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return (
    [year, month, day].map(formatNumber).join("/") +
    " " +
    [hour, minute, second].map(formatNumber).join(":")
  );
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : "0" + n;
};

function date(timestamp = new Date().getTime()) {
  var d = new Date(timestamp); //根据时间戳生成的时间对象
  var month = d.getMonth() + 1;
  var day = d.getDate();
  var date =
    d.getFullYear() +
    "-" +
    (month <= 9 ? "0" + month : month) +
    "-" +
    (day <= 9 ? "0" + day : day);
  return date;
}

function time(timestamp = new Date().getTime()) {
  var d = new Date(timestamp); //根据时间戳生成的时间对象
  var minute = d.getMinutes() + 1;
  var second = d.getSeconds();
  var date =
    d.getHours() +
    ":" +
    (minute <= 9 ? "0" + minute : minute) +
    ":" +
    (second <= 9 ? "0" + second : second);
  return date;
}

function getStorage(key, defaultValue = {}) {
  return new Promise((resolve) => {
    wx.getStorage({
      key,
      success(res) {
        resolve(res.data);
      },
      fail(res) {
        resolve(defaultValue);
      },
    });
  });
}

function setStorage(key, data) {
  return new Promise((resolve, reject) => {
    wx.setStorage({
      key,
      data,
      success(res) {
        resolve(res.data);
      },
      fail(res) {
        console.log("存储" + key + "失败");
        reject(res);
      },
    });
  });
}


import Dialog from '../../dist/vantui/dialog/dialog';
import Toast from '../../dist/vantui/toast/toast';

function show_message(message) {
  Toast(message);
}

function show_toast(message = "加载中...", type = "loading", duration = 1500, mask = false, forbidClick = true) {
  if (type == "loading")
    duration = 15000;
  if (type != 'loading') {
    show_message(message);
  } else {
    Toast({
      type,
      forbidClick,
      message,
      duration,
      mask,
      onClose: () => {
        // console.log('执行OnClose函数');
      },
    });
  }
}

async function show_dialog(message, title = "消息", confirmButtonText = "我知道了", messageAlign = "center") {
  return Dialog.alert({
    title,
    message,
    confirmButtonText,
    messageAlign,
  });
}

function hide_toast() {
  Toast.clear();
  wx.hideNavigationBarLoading();
  wx.stopPullDownRefresh();
}

//所有需要显示给用户看的提示信息都要用这个函数生成信息
function message(msg) {
  return {
    message: msg,
    show: true,
  };
}

//判断是否需要重新加载用户信息
async function checkRelogin() {
  if (getApp().globalData.needRelogin) {
    let number = getApp().globalData.userInfo.number;
    let password = getApp().globalData.userInfo.password;
    await token_get(number, password);
  }
}

async function checkUserAgreement() {
  if (!getApp().globalData.userSetting.agreedUserLicense) {
    //兼容老版本数据
    if (getApp().globalData.agreedUserLicense) {
      getApp().globalData.userSetting.agreedUserLicense = getApp().globalData.agreedUserLicense;
      await setStorage("userSetting", userSetting);
      return Promise.reject();
    }
    await show_dialog(
      "应学校教务处要求，你必须先阅读并同意《用户许可协议》中所列协议之后，才能继续使用微校园所提供的的服务"
    );
    wx.switchTab({
      url: "../person/person",
    });
    wx.clearStorage();
    initGlobalData();
    return Promise.reject();
  }
}

function dealWithUrl(url, idx) {
  if (url.startsWith("http")) {
    return url;
  } else {
    return getApp().globalData.serverPool[idx ? idx : 0] + url;
  }
}

function getServerIdx() {
  let idx = 0;
  if (getApp().globalData.online && getApp().globalData.userInfo.number)
    idx =
      parseInt(getApp().globalData.userInfo.number.charAt(3)) %
      getApp().globalData.serverPool.length;
  return idx;
}

function vcodeServer() {
  return getApp().globalData.resourceUrlBase;
}

/**
 * 适用于用户手动输入验证码版本的request函数
 * @param {*} url 请求的url
 * @param {*} data 请求参数
 */
async function request(url, data) {
  //判断是否需要重新登录
  await checkRelogin();
  data = data ? data : {};
  console.log("vis: " + url);
  if (getApp().globalData.userInfo && getApp().globalData.userInfo.token) {
    //用户是否已同意用户许可协议、默认带token
    await checkUserAgreement();
    data.token = getApp().globalData.userInfo.token;
  }
  return await new Promise((resolve, reject) => {
    wx.request({
      url: dealWithUrl(url, getServerIdx()),
      data,
      async success(res) {
        if (res.statusCode != 200) {
          //服务器发生未知错误,无法正常响应用户请求
          console.log(res);
          reject(
            message(
              "服务器无法正常响应该请求，请稍后再试或者联系管理员,错误码:" +
              res.statusCode +
              ""
            )
          );
          return;
        }
        if (res.data.result == "success") {
          resolve(res);
          return;
        }
        //如果token无效,重新登录
        if (res.data.result == "invalid_token") {
          initGlobalData();
          wx.clearStorage();
          return;
        }
        //非第一次请求时提示密码错误，则用户可能更改过密码
        // console.log( res.data.result);
        if (
          res.data.result == "invalid_password" &&
          getApp().globalData.userInfo.online
        ) {
          reject(
            message("您的Ehall密码可能已经变更，请在设置中修改密码后重试")
          );
          return;
        }
        //直接显示服务器返回的信息
        if (res.data.message) {
          reject(message(res.data.message));
          return;
        }
        reject(message("请求失败"));
      },
      fail(e) {
        reject(message("网络连接异常或请求超时"));
      },
    });
  });
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function doAfter(f, interval = 1000) {
  setTimeout(function () {
    f();
  }, interval);
}

async function getVcodeId() {
  if (
    !getApp().globalData.userInfo ||
    (getApp().globalData.userInfo && !getApp().globalData.userInfo.vcode_id)
  ) {
    try {
      var res = await request("vcode_id");
      if (!getApp().globalData.userInfo) getApp().globalData.userInfo = {};
      getApp().globalData.userInfo.vcode_id = res.data.attach;
      setStorage("userInfo", getApp().globalData.userInfo);
      console.log("newvocde_id : " + getApp().globalData.userInfo.vcode_id);
    } catch (error) {
      console.log(error);
      errorHandler(error);
    }
  }
  return getApp().globalData.userInfo.vcode_id;
}

async function setVcode(vcode) {
  await request("set_vcode", {
    vcode_id: await getVcodeId(),
    vcode,
  });
}

async function needVCode(uid = getApp().globalData.userInfo.number) {
  var res = await request("needVCode_v2", {
    uid,
  });
  return res.data.attach;
}

//统一网络请求异常处理
function errorHandler(error) {
  if (!error) {
    return;
  }
  console.log(error);
  if (error.show) {
    show_message(error.message);
  }
}

//检查是否有某项权限
function authorize(scope) {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting[scope]) {
          wx.authorize({
            scope,
            success() {
              resolve();
            },
            fail() {
              reject();
            },
          });
        } else {
          resolve();
        }
      },
    });
  });
}

//滚动到底部
function toPageBottom() {
  let query = wx.createSelectorQuery();
  query.select("#bottom").boundingClientRect();
  // 执行查询
  query.exec((ele) => {
    let e = ele[0];
    wx.pageScrollTo({
      scrollTop: e.top,
    });
  });
}

function initGlobalData() {
  getApp().globalData = {
    userInfo: {}, //用户数据对象
    gradeInfo: null,
    exam: null,
    name: null,
    online: false,
    number: null,
    password: null,
    token: null,
    needRelogin: false,
    historyMessage: {},
    userSetting: getApp().globalData.userSetting,
    screenWidth: getApp().globalData.screenWidth,
    screenHeight: getApp().globalData.screenHeight,
    systemInfo: getApp().globalData.systemInfo,
    resourceUrlBase: getApp().globalData.resourceUrlBase,
    pushMessages: null, //上次推送消息
    serverPool: getApp().globalData.serverPool,
    year: 2016, //入学年份
    course: [], //用户课程
    term: 0, //用户当前学期
    task: [false, false, false, false, false], //一个全局变量，当重新登录或者切换账号后，用来告诉某个页面是否需要刷新本页面（小程序导航页不能刷新，只能通过生命周期函数改变数据）。第一个对应index页面，后面的好像还没用到
    libraryInfo: null, //图书馆信息
    passwords: {}, //密码对象，保存了图书馆密码等和非统一登录密码的密码，如图书馆密码访问 passwords.library
    needRelogin: false, //是否需要重新登录
    userSetting: {}, //用户对小程序的设置，如是否在课表显示未安排课程
    gradeReport: [],//用户的成绩报告
  };
}

module.exports = {
  formatTime,
  setStorage,
  getStorage,
  show_dialog,
  show_message,
  show_toast,
  hide_toast,
  request,
  sleep,
  doAfter,
  authorize,
  errorHandler,
  message,
  getAll,
  login,
  signup,
  toPageBottom,
  initGlobalData,
  date,
  time,
  setVcode,
  needVCode,
  getVcodeId,
  getServerIdx,
  vcodeServer,
  dealWithUserInfo,
};
